<!-- 文书 -->
<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 文书树 -->
      <el-col :lg="4" :xs="24" class="mb-[12px]">
        <dept-tree
          v-model="queryParams.instrumentTypeId"
          @node-click="handleQuery"
        />
      </el-col>
      <!-- 文书代写列表 -->
      <el-col :lg="20" :xs="24">
        <div class="search-container">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="关键字" prop="instrumentName">
              <el-input
                v-model="queryParams.instrumentName"
                placeholder="文书名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <i-ep-search />
                搜索
              </el-button>
              <el-button @click="handleResetQuery">
                <i-ep-refresh />
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <el-card shadow="never" class="table-container">
          <template #header>
            <div class="flex-x-between">
              <div>
                <el-button type="success" @click="handleOpenDialog()">
                  <i-ep-plus />
                  新增
                </el-button>
                <el-button
                  type="danger"
                  :disabled="removeIds.length === 0"
                  @click="handleDelete()"
                >
                  <i-ep-delete />
                  批量删除
                </el-button>
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="pageData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              key="id"
              label="编号"
              align="center"
              prop="id"
              width="120"
            />
            <el-table-column
              key="instrumentName"
              label="文书名称"
              align="center"
              prop="instrumentName"
              width="240"
            />

            <el-table-column
              label="文书分类"
              align="center"
              prop="instrumentTypeName"
              width="240"
            />

            <el-table-column
              label="领域"
              align="center"
              prop="businessCategoryName"
              width="120"
            />

            <el-table-column
              label="费用"
              align="center"
              prop="expenses"
              width="120"
            />

            <el-table-column label="创建时间" align="center">
              <template #default="scope">
                <text>
                  {{
                    new Date(scope.row.createdAt)
                      .toISOString()
                      .replace("T", " ")
                      .substring(0, 19)
                  }}
                </text>
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="180">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleOpenDialog(scope.row)"
                >
                  <i-ep-edit />
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(scope.row.id)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.current"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 文书代写表单弹窗 -->
    <el-drawer
      v-model="dialog.visible"
      :title="dialog.title"
      append-to-body
      @close="handleCloseDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="文书名称" prop="instrumentName">
          <el-input
            v-model="formData.instrumentName"
            placeholder="请输入文书名称"
          />
        </el-form-item>

        <el-form-item label="文书分类" prop="instrumentTypeId">
          <el-cascader
            v-model="formData.instrumentTypeId"
            :options="insData"
            style="width: 100%"
            :props="cascaderProps"
            :show-all-levels="false"
            @change="insSelectChange"
          />
        </el-form-item>

        <el-form-item label="领域" prop="newBusinessCategoryName">
          <el-select
            v-model="formData.newBusinessCategoryName"
            :multiple="false"
            placeholder="请选择"
            @change="categoryChange"
          >
            <el-option
              v-for="item in bussinessData"
              :key="item.id"
              :label="item.categoryName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="文书费用" prop="expenses">
          <el-input v-model="formData.expenses" placeholder="请输入文书费用" />
        </el-form-item>
        <el-form-item label="收费单位:次" prop="expensesUnit">
          <el-input
            v-model="formData.expensesUnit"
            placeholder="请输入文书收费单位:次"
          />
        </el-form-item>
        <el-form-item label="以售数量" prop="soldTimes">
          <el-input v-model="formData.soldTimes" placeholder="请输入以售数量" />
        </el-form-item>
        <el-form-item label="文书详情" prop="instrumentDetail">
          <el-input
            v-model="formData.instrumentDetail"
            placeholder="请输入文书详情"
          />
        </el-form-item>
        <el-form-item label="文书封面" prop="newInstrumentImgUrl">
          <img-upload
            v-if="formData.isUpload"
            :list="formData.newInstrumentImgUrl"
            @update-uploaded="updateUpload"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Customers",
  inheritAttrs: false,
});

import instrumentAPI, {
  InstrumentQuery,
  InstrumentForm,
  InstrumentVO,
} from "@/api/instruments";
import inscategoryAPI from "@/api/inscategory";
import instypeAPI from "@/api/instype";
import lawyerAPI, { LawyerPageVO, LawyerPageQuery } from "@/api/lawyer";
import bussinessAPI, { BussinessVO } from "@/api/business";

const queryFormRef = ref(ElForm);
const userFormRef = ref(ElForm);

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);
const pageData = ref<InstrumentVO[]>();
/** 文书分类列表 */
const insData = ref<any>([]);
const cascaderProps = {
  label: "category",
  value: "id",
  children: "children",
  emitPath: false,
};
/** 业务列表 */
const bussinessData = ref<BussinessVO[]>();

/** 文书代写查询参数  */
const queryParams = reactive<InstrumentQuery>({
  current: 1,
  pageSize: 10,
  instrumentName: "",
  instrumentCategory: "",
  instrumentTypeId: undefined,
});

/**  文书代写弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

// 文书代写表单数据
const formData = reactive<InstrumentForm>({
  instrumentTypeId: undefined,
  instrumentTypeName: "",
  instrumentCategory: undefined,
  instrumentCategoryName: "",
  expenses: undefined,
  expensesUnit: "",
  instrumentName: "",
  instrumentDetail: "",
  instrumentFileUrl: "",
  soldTimes: undefined,
  instrumentImgUrl: "",
  businessCategoryId: undefined,
  businessCategoryName: "",
  newBusinessCategoryName: "",
  id: undefined,
  isUpload: false,
  newInstrumentImgUrl: [],
});

/** 文书代写表单校验规则  */
const rules = reactive({
  instrumentName: [
    { required: true, message: "文书名称不能为空", trigger: "blur" },
  ],
  instrumentTypeId: [
    { required: true, message: "文书分类不能为空", trigger: "blur" },
  ],
  expenses: [{ required: true, message: "费用不能为空", trigger: "blur" }],
  instrumentDetail: [
    { required: true, message: "详情不能为空", trigger: "blur" },
  ],
  newBusinessCategoryName: [
    { required: true, message: "业务领域不能为空", trigger: "blur" },
  ],
  newInstrumentImgUrl: [
    { required: false, message: "文书封面不能为空", trigger: "blur" },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  instrumentAPI
    .getInstrument(queryParams)
    .then((data) => {
      console.log(data, "文书列表");
      pageData.value = data.records;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/**
 * 打开弹窗
 *
 * @param id 文书代写ID
 */
async function handleOpenDialog(val?: any) {
  dialog.visible = true;
  await inscategoryAPI.getInsCategory().then((data) => {
    insData.value = data.map((item) => ({
      ...item,
      children: [],
    }));
  });
  await instypeAPI.getInstype().then((data) => {
    data.forEach((newItem) => {
      let matchingItem = insData.value.find(
        (item: any) => item.category === newItem.categoryName
      );
      if (matchingItem) {
        matchingItem.children.push({
          id: newItem.id,
          category: newItem.typeName,
        });
      }
    });
  });
  bussinessData.value = await bussinessAPI.getBussiness();
  if (val) {
    // console.log(val, "打开弹窗");
    dialog.title = "修改文书代写";
    Object.assign(formData, {
      ...val,
      instrumentTypeId: Number(val.instrumentTypeId),
    });
    if (val.instrumentImgUrl != "" && formData.newInstrumentImgUrl) {
      formData.newInstrumentImgUrl.push(val.instrumentImgUrl);
    }
    formData.isUpload = true;
    formData.newBusinessCategoryName = val.businessCategoryId;
  } else {
    formData.isUpload = true;
    dialog.title = "新增文书代写";
  }
}
/** 选中文书分类时触发 */
const insSelectChange = (item: any) => {
  let ins = findById(insData.value, item);
  formData.instrumentCategory = ins.found.id;
  formData.instrumentCategoryName = ins.found.category;
  formData.instrumentTypeName = ins.child.category;
  // console.log(ins, formData, "文书选择");
};
/** 遍历找到对应的城市数据 */
function findById(arr: any, id: number) {
  let found = arr.find((parent: { children: any[] }) => {
    return parent.children.find((child: { id: number }) => child.id === id);
  });
  if (found) {
    let child = found.children.find((child: { id: number }) => child.id === id);
    return {
      found,
      child,
    };
  }
  return { found: undefined };
}
/** 业务分类选泽时触发 */
const categoryChange = (val: any) => {
  // formData.businessCategoryId = val.join(",");
  formData.businessCategoryId = val;
  bussinessData.value?.forEach((item) => {
    if (item.id === val) {
      formData.businessCategoryName = item.categoryName;
    }
  });
  // console.log(val, formData, "业务选择");
};
/** 上传图片返回函数 */
const updateUpload = (item: string[]) => {
  formData.newInstrumentImgUrl = item;
  if (item.length >= 1) {
    formData.instrumentImgUrl = item[0];
  } else {
    formData.instrumentImgUrl = "";
  }
};
/** 关闭弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  formData.id = undefined;
  formData.isUpload = false;
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      formData.newBusinessCategoryName = undefined;
      loading.value = true;
      instrumentAPI
        .updateInstrument(formData)
        .then(() => {
          if (userId) {
            ElMessage.success("修改文书代写成功");
          } else {
            ElMessage.success("新增文书代写成功");
          }
          handleCloseDialog();
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    }
  });
}, 3000);

/** 删除文书代写 */
function handleDelete(id?: number) {
  const userIds = [id || removeIds.value].join(",");

  ElMessageBox.confirm("确认删除文书代写?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      instrumentAPI
        .deleteInstrument(userIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  // handleQuery();
});
</script>
